package com.bupt.ilink.controller;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bupt.ilink.entity.*;
import com.bupt.ilink.service.DatasetMetadataService;
import com.bupt.ilink.service.DatasetTagsService;
import com.bupt.ilink.service.MinioService;
import com.bupt.ilink.utils.R;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.jetbrains.annotations.NotNull;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.awt.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.stream.Collectors;

@RestController
public class DatasetMetadataController {
    @Autowired
    private DatasetMetadataService datasetMetadataService;

    @Autowired
    private DatasetTagsService datasetTagsService;

    @Autowired
    private MinioService minioService;
    private static final Logger logger = LoggerFactory.getLogger(DatasetMetadataController.class);


    private final Snowflake snowflake = IdUtil.getSnowflake(1, 1);

    private static final int BATCH_SIZE = 500; // 批量大小，可根据实际情况调整

    /**
     * @author dzy
     * @return 最常使用的8个标签(List<String>形式)
     */
    @GetMapping("/getCommonDatasetTags")
    public R getCommonDatasetTags(){
        try {
            return R.ok(datasetTagsService.getCommonTags());
        } catch(Exception e){
            return R.failure("内部服务器错误：" + e);
        }
    }

    // 增加数据集的download_num, 并且返回下载链接（公开数据集是直接跳转）
    @PostMapping("/downloadDataset")
    public R downloadDataset(@RequestBody String jsonString) {

        JSONObject jsonObject = new JSONObject(jsonString);
        String targetId = jsonObject.getString("targetId");

        // 获取数据集元数据
        DatasetMetadata metadata = datasetMetadataService.getById(targetId);
        System.out.println("下载量");
        System.out.println(targetId);
        System.out.println(metadata);

        if (metadata != null && "public".equals(metadata.getAccessLevel())) {
            // 增加下载次数
            datasetMetadataService.incrementDownloadNum(Long.valueOf(targetId));

            // 返回下载链接
            return R.ok(metadata.getUrl());
        } else {
            return R.failure("数据集不存在或不是公开数据集");
        }
    }

    // 查询所有 公开数据集 元数据信息
    @GetMapping("/getPublicDatasets")
    public IPage<DatasetResponse> getPublicDatasets(@RequestParam int page) {
        int size = 12;
        // 创建分页对象
        Page<DatasetMetadata> pageRequest = new Page<>(page, size);

        // 分页查询公开的数据集
        IPage<DatasetMetadata> metadataPage = datasetMetadataService.getPublicDatasetsByPage(pageRequest);

        // 将结果转换为 DatasetResponse 格式
        IPage<DatasetResponse> responsePage = metadataPage.convert(metadata -> {
            List<DatasetTags> tagsList = datasetTagsService.getTagsByDatasetId(metadata.getDatasetId());
            List<String> tags = tagsList.stream().map(DatasetTags::getTag).collect(Collectors.toList());

            DatasetResponse response = new DatasetResponse();
            response.setDatasetId(metadata.getDatasetId());
            response.setName(metadata.getName());
            response.setDescription(metadata.getDescription());
            response.setCreatorName(metadata.getCreatorName());
            response.setCreatedTime(metadata.getCreatedTime());
            response.setUpdatedTime(metadata.getUpdatedTime());
            response.setStatus(metadata.getStatus());
            response.setAccessLevel(metadata.getAccessLevel());
            response.setImagePath(metadata.getImagePath());
            response.setUrl(metadata.getUrl());
            response.setReviewStatus(metadata.getReviewStatus());
            response.setDownloadNum(metadata.getDownloadNum());
            response.setClickNum(metadata.getClickNum());
            response.setShareNum(metadata.getShareNum());
            response.setFavoriteNum(metadata.getFavoriteNum());
            response.setTags(tags);
            return response;
        });

        return responsePage;
    }

    //    用于测试
    @GetMapping("/validateObjectExistence")
    public ResponseEntity<String> validateObjectExistence() {
        System.out.println("测试图片");
        minioService.validateObjectExistence();
        return ResponseEntity.ok("Validation complete. Check logs for details.");
    }

    //    查询所有 公开数据集 图片
//    @GetMapping("/getPublicDatasetsImages")
//    public List<DatasetFiles> getPublicDatasetsImages() {
//        // 获取所有DatasetMetadata实体，并过滤accessLevel为'public'的
//        List<DatasetMetadata> metadataList = datasetMetadataService.list()
//                .stream()
//                .filter(metadata -> "public".equals(metadata.getAccessLevel()))
//                .collect(Collectors.toList());
//
//        ExecutorService executor = Executors.newFixedThreadPool(10); // 创建线程池
//        List<Future<DatasetFiles>> futures = metadataList.stream()
//                .map(metadata -> executor.submit(() -> {
//                    Long datasetId = metadata.getDatasetId();
//                    String url = minioService.getImageUrlWithAnyFormat("image/" + datasetId);
//                    logger.info("Generated URL for dataset {}: {}", datasetId, url);
//                    return new DatasetFiles(datasetId, url);
//                }))
//                .collect(Collectors.toList());
//
//        // 等待所有任务完成并收集结果
//        List<DatasetFiles> result = futures.stream()
//                .map(future -> {
//                    try {
//                        return future.get();
//                    } catch (Exception e) {
//                        logger.error("Error fetching dataset file", e);
//                        return null;
//                    }
//                })
//                .filter(response -> response != null && response.getUrl() != null)
//                .collect(Collectors.toList());
//
//        executor.shutdown(); // 关闭线程池
//        return result;
//    }

    //    根据数据集ID 返回数据集详情文件
//    @GetMapping("getDatasetFiles")
//    public DatasetFiles getDatasetFiles(Long targetDatasetId) {
//        //  判断这个targetDatasetId对应的数据集是public，private还是team
//        DatasetMetadata metadata = datasetMetadataService.getById(targetDatasetId);
//        if (metadata == null) {
//            // 返回空或抛出异常
//            return null;
//        }
//        String accessLevel = (String) metadata.getAccessLevel();
//
//        //  如果是public，直接从minio数据库中找到这个文件。
//        //  路径是files/targetDatasetId
//        if ("public".equals(accessLevel)) {
//            // 从 MinIO 数据库中找到对应文件
//            String url = minioService.getFileUrlWithAnyFormat("files/" + targetDatasetId);
//            if (url != null) {
//                return new DatasetFiles(targetDatasetId, url);
//            }
//        }
//
//        return null;
//    }

    //  杂糅查找wenbe
    @GetMapping("/searchDatasets")
    public Page<DatasetResponse> searchDatasets(
            @RequestParam(required = false) String keywords,
            @RequestParam(required = false) String tag,
            @RequestParam(required = false) String sortBy,
            @RequestParam(defaultValue = "1") int page) {

        int size = 12;
        List<DatasetMetadata> metadataList = new ArrayList<>();
        Set<Long> datasetIds = new HashSet<>();
        System.out.println("杂糅输出");
        System.out.println(tag);
        System.out.println(keywords);

        if (tag == null && keywords == null) {
            // 如果没有任何条件，则查询所有公开数据集
            Page<DatasetMetadata> metadataPage = datasetMetadataService.page(
                    new Page<>(page, size),
                    new QueryWrapper<DatasetMetadata>().eq("access_level", "public")
            );

            System.out.println(metadataPage);
            return toDatasetResponsePage(metadataPage, sortBy);
        }

        // 根据标签查询
        if (tag != null && !tag.trim().isEmpty()) {
            List<DatasetTags> tagsList = datasetTagsService.getTagsByTags(tag);
            if (tagsList.isEmpty()) {
                return new Page<>(); // 如果找不到标签，返回空结果
            }
            Set<Long> tagDatasetIds = tagsList.stream().map(DatasetTags::getDatasetId).collect(Collectors.toSet());
            datasetIds.addAll(tagDatasetIds);
        }

        // 根据关键词查询
        if (keywords != null && !keywords.trim().isEmpty()) {
            List<DatasetMetadata> keywordMetadataList = datasetMetadataService.getDatasetsByKeywords(keywords);
            if (keywordMetadataList.isEmpty()) {
                return new Page<>(); // 如果找不到关键词，返回空结果
            }
            Set<Long> keywordDatasetIds = keywordMetadataList.stream().map(DatasetMetadata::getDatasetId).collect(Collectors.toSet());
            if (!datasetIds.isEmpty()) {
                datasetIds.retainAll(keywordDatasetIds);
                if (datasetIds.isEmpty()) {
                    return new Page<>(); // 如果交集为空，返回空结果
                }
            } else {
                datasetIds.addAll(keywordDatasetIds);
            }
        }

        // 如果没有任何查询条件，直接返回空结果
        if (datasetIds.isEmpty()) {
            return new Page<>();
        } else {
            metadataList = datasetMetadataService.getDatasetsByIds(new ArrayList<>(datasetIds));
        }

        // 过滤出 access_level 为 public 的数据集
        List<DatasetMetadata> publicMetadataList = metadataList.stream()
                .filter(metadata -> "public".equals(metadata.getAccessLevel()))
                .collect(Collectors.toList());

        // 创建线程池
        ExecutorService executor = Executors.newFixedThreadPool(10);

        // 并行处理，获取 MinIO 中的 URL
        List<Future<DatasetResponse>> futures = publicMetadataList.stream()
                .map(metadata -> executor.submit(() -> {
                    String datasetId = metadata.getDatasetId().toString();
                    String url = minioService.getImageUrlWithAnyFormat("image/" + datasetId);
                    logger.info("Generated URL for dataset {}: {}", datasetId, url);

                    List<String> tags = datasetTagsService.getTagsByDatasetId(metadata.getDatasetId()).stream()
                            .map(DatasetTags::getTag)
                            .collect(Collectors.toList());

                    DatasetResponse response = new DatasetResponse();
                    response.setDatasetId(metadata.getDatasetId());
                    response.setName(metadata.getName());
                    response.setTags(tags);
                    response.setDescription(metadata.getDescription());
                    response.setCreatorName(metadata.getCreatorName());
                    response.setCreatedTime(metadata.getCreatedTime());
                    response.setUpdatedTime(metadata.getUpdatedTime());
                    response.setStatus(metadata.getStatus());
                    response.setAccessLevel(metadata.getAccessLevel());
                    response.setImagePath(url);
                    response.setUrl(metadata.getUrl());
                    response.setReviewStatus(metadata.getReviewStatus());
                    response.setDownloadNum(metadata.getDownloadNum());
                    response.setClickNum(metadata.getClickNum());
                    response.setShareNum(metadata.getShareNum());
                    response.setFavoriteNum(metadata.getFavoriteNum());

                    return response;
                }))
                .collect(Collectors.toList());

        // 等待所有任务完成并收集结果
        List<DatasetResponse> result = futures.stream()
                .map(future -> {
                    try {
                        return future.get();
                    } catch (Exception e) {
                        logger.error("Error fetching dataset response", e);
                        return null;
                    }
                })
                .filter(response -> response != null && response.getUrl() != null)
                .collect(Collectors.toList());

        // 关闭线程池
        executor.shutdown();

        // 根据排序参数进行排序（倒序）
        Comparator<DatasetResponse> comparator = Comparator.comparing(DatasetResponse::getDatasetId); // 默认按 datasetId 升序排序
        if ("download_num".equalsIgnoreCase(sortBy)) {
            comparator = Comparator.comparing(DatasetResponse::getDownloadNum, Comparator.nullsLast(Long::compareTo)).reversed();
        } else if ("created_time".equalsIgnoreCase(sortBy)) {
            comparator = Comparator.comparing(DatasetResponse::getCreatedTime, Comparator.nullsLast(Date::compareTo)).reversed();
        }

        result.sort(comparator);

        // 分页
        int start = (page - 1) * size;
        int end = Math.min(start + size, result.size());
        List<DatasetResponse> paginatedResult = result.subList(start, end);

        // 返回分页结果
        Page<DatasetResponse> pagedResult = new Page<>(page, size, result.size());
        pagedResult.setRecords(paginatedResult);
        return pagedResult;
    }

    private Page<DatasetResponse> toDatasetResponsePage(Page<DatasetMetadata> metadataPage, String sortBy) {
        List<DatasetMetadata> records = metadataPage.getRecords();

        ExecutorService executor = Executors.newFixedThreadPool(10);
        List<Future<DatasetResponse>> futures = records.stream()
                .map(metadata -> executor.submit(() -> {
                    String datasetId = metadata.getDatasetId().toString();
                    String url = minioService.getImageUrlWithAnyFormat("image/" + datasetId);
                    List<String> tags = datasetTagsService.getTagsByDatasetId(metadata.getDatasetId()).stream()
                            .map(DatasetTags::getTag)
                            .collect(Collectors.toList());

                    DatasetResponse response = new DatasetResponse();
                    response.setDatasetId(metadata.getDatasetId());
                    response.setName(metadata.getName());
                    response.setTags(tags);
                    response.setDescription(metadata.getDescription());
                    response.setCreatorName(metadata.getCreatorName());
                    response.setCreatedTime(metadata.getCreatedTime());
                    response.setUpdatedTime(metadata.getUpdatedTime());
                    response.setStatus(metadata.getStatus());
                    response.setAccessLevel(metadata.getAccessLevel());
                    response.setImagePath(url);
                    response.setUrl(metadata.getUrl());
                    response.setReviewStatus(metadata.getReviewStatus());
                    response.setDownloadNum(metadata.getDownloadNum());
                    response.setClickNum(metadata.getClickNum());
                    response.setShareNum(metadata.getShareNum());
                    response.setFavoriteNum(metadata.getFavoriteNum());

                    return response;
                }))
                .collect(Collectors.toList());

        List<DatasetResponse> datasetResponses = futures.stream()
                .map(future -> {
                    try {
                        return future.get();
                    } catch (Exception e) {
                        e.printStackTrace();
                        return null;
                    }
                })
                .filter(Objects::nonNull)
                .collect(Collectors.toList());

        executor.shutdown();

        // 根据排序参数进行排序（倒序）
        Comparator<DatasetResponse> comparator = Comparator.comparing(DatasetResponse::getDatasetId); // 默认按 datasetId 升序排序
        if ("download_num".equalsIgnoreCase(sortBy)) {
            comparator = Comparator.comparing(DatasetResponse::getDownloadNum, Comparator.nullsLast(Long::compareTo)).reversed();
        } else if ("created_time".equalsIgnoreCase(sortBy)) {
            comparator = Comparator.comparing(DatasetResponse::getCreatedTime, Comparator.nullsLast(Date::compareTo)).reversed();
        }

        datasetResponses.sort(comparator);

        // 构建分页结果
        Page<DatasetResponse> responsePage = new Page<>(metadataPage.getCurrent(), metadataPage.getSize(), metadataPage.getTotal());
        responsePage.setRecords(datasetResponses);

        return responsePage;
    }

    @GetMapping("/getDatasetStatistics")
    public R getDatasetStatistics() {
        // 获取 DatasetMetadata 的总数
        long metadataCount = datasetMetadataService.count();

        // 获取 DatasetTags 的种类总数
        long tagsCount = datasetTagsService.getTagsCount();

        // 返回统计信息
        return R.ok("数据集数量: " + metadataCount + ", 标签种类个数: " + tagsCount);
    }

    //    批量插入 公开数据集元数据信息
    @PostMapping("/batchInsertPublicDatasets")
    public R batchInsertPublicDatasets(@RequestBody List<DatasetMetadata> metaDatas) {
        // 使用雪花算法snowflake为每个记录生成唯一的 UUID
        for (DatasetMetadata metadata : metaDatas) {
            metadata.setDatasetId(Long.valueOf(snowflake.nextId()));
        }

        boolean isSuccess = datasetMetadataService.saveBatch(metaDatas);
        if(isSuccess){
            return R.ok("公开数据集 批量插入成功");
        }else{
            return R.failure("公开数据集 批量插入失败");
        }
    }

    //    用csv批量插入 公开数据集元数据信息
    @PostMapping("/csvBatchInsertPublicDatasets")
    public R csvBatchInsertPublicDatasets(@RequestBody MultipartFile file) {

        Set<String> existingNames = new HashSet<>(datasetMetadataService.getAllNames()); // 查询数据库中的所有名称，确保不重复
        List<DatasetMetadata> metadataList = new ArrayList<>();
        List<DatasetTags> tagsList = new ArrayList<>();

        // 支持的日期格式
        List<SimpleDateFormat> dateFormats = Arrays.asList(
                new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"),
                new SimpleDateFormat("yyyy/M/d H:mm"),
                new SimpleDateFormat("yyyy/M/dd H:mm"),
                new SimpleDateFormat("yyyy/MM/dd H:mm:ss"),
                new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"), // 添加你需要的格式
                new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") // 支持毫秒的格式
        );

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(file.getInputStream(), StandardCharsets.UTF_8));
             CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT.withFirstRecordAsHeader())) {

            // 打印列名称
            System.out.println("CSV文件头部: " + csvParser.getHeaderMap().keySet());

            int count = 0;

            for (CSVRecord record : csvParser) {
                // 确保name列不为空
                String name = record.get("name");
                if (name == null || name.trim().isEmpty() || existingNames.contains(name)) {
                    System.out.println("跳过行，name为空或重复: " + record.toString());
                    continue; // 跳过name为空或重复的行
                }

                existingNames.add(name); // 添加到已存在的名称集合中

                DatasetMetadata metadata = new DatasetMetadata();
                metadata.setDatasetId(snowflake.nextId());
                metadata.setImagePath(record.isSet("imagePath") ? record.get("imagePath") : "");
                metadata.setName(name);
                metadata.setDescription(record.isSet("description") ? record.get("description") : "");
                metadata.setCreatorName(record.isSet("creatorName") ? record.get("creatorName") : "");

                // Parse date
                Date createdDate = null;
                String createdTime = record.isSet("createdTime") ? record.get("createdTime") : null;
                if (createdTime != null && !createdTime.trim().isEmpty()) {
                    for (SimpleDateFormat dateFormat : dateFormats) {
                        try {
                            createdDate = dateFormat.parse(createdTime);
                            break; // 如果成功解析则跳出循环
                        } catch (ParseException e) {
                            // 忽略并尝试下一个格式
                        }
                    }
                }
                // 专门针对 paperwithcode 的情况，如果 createdTime 为空，设置为当前日期
                if (createdDate == null) {
                    if (createdTime == null) {
                        System.out.println("日期为空，使用当前日期");
                        createdDate = new Date(); // 使用当前日期
                    } else {
                        System.out.println("跳过行，日期格式错误: " + createdTime);
                        continue; // 跳过日期格式错误的行
                    }
                }
                metadata.setCreatedTime(createdDate);
                metadata.setUpdatedTime(createdDate); // 设置updatedTime为createdTime
                metadata.setStatus("active"); // 设置status为"active"
                metadata.setAccessLevel("public"); // 设置accessLevel为"public"
                metadata.setClickNum(0L);
                metadata.setShareNum(0L);
                metadata.setDownloadNum(0L);
                metadata.setFavoriteNum(0L);

                metadata.setUrl(record.isSet("url") ? record.get("url") : "");

                metadataList.add(metadata);

                String tagsString = record.isSet("tags") ? record.get("tags") : "";
                String[] tags = tagsString.split(",");
                for (String tag : tags) {
                    DatasetTags datasetTag = new DatasetTags();
                    datasetTag.setTagId(Long.valueOf(snowflake.nextId()));
                    datasetTag.setDatasetId(metadata.getDatasetId());
                    datasetTag.setTag(tag.trim());
                    tagsList.add(datasetTag);
                }

                count++;
                if (count % BATCH_SIZE == 0) {
                    // 批量插入
                    datasetMetadataService.saveBatch(metadataList);
                    datasetTagsService.saveBatch(tagsList);
                    metadataList.clear();
                    tagsList.clear();
                    System.out.println("已处理 " + count + " 条记录");
                }
            }

            // 插入剩余记录
            if (!metadataList.isEmpty()) {
                datasetMetadataService.saveBatch(metadataList);
                datasetTagsService.saveBatch(tagsList);
                System.out.println("已处理剩余 " + metadataList.size() + " 条记录");
            }

        } catch (IOException e) {
            e.printStackTrace();
            return R.failure("文件处理失败");
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            return R.failure("CSV文件头部列名称不匹配: " + e.getMessage());
        }

        return R.ok("公开数据集批量插入成功");
    }

    // 根据关键词 返回数据集（公开）
    @GetMapping("/getDatasetsByKeywords")
    public List<DatasetResponse> getDatasetsByKeywords(@RequestParam String keywords) {
        // 查询所有匹配关键词的公开数据集元数据
        List<DatasetMetadata> metadataList = datasetMetadataService.getDatasetsByKeywords(keywords);

        // 过滤出 access_level 为 public 的数据集
        List<DatasetMetadata> publicMetadataList = metadataList.stream()
                .filter(metadata -> "public".equals(metadata.getAccessLevel()))
                .collect(Collectors.toList());

        // 创建线程池
        ExecutorService executor = Executors.newFixedThreadPool(6);

        // 并行处理，获取 MinIO 中的 URL
        List<Future<DatasetResponse>> futures = publicMetadataList.stream()
                .map(metadata -> executor.submit(() -> {
                    String datasetId = metadata.getDatasetId().toString();
                    String url = minioService.getImageUrlWithAnyFormat("image/" + datasetId);
                    logger.info("Generated URL for dataset {}: {}", datasetId, url);

                    DatasetResponse response = new DatasetResponse();
                    response.setDatasetId(metadata.getDatasetId());
                    response.setName(metadata.getName());
                    response.setTags(getTagsByDatasetId(metadata.getDatasetId())); // 获取标签
                    response.setDescription(metadata.getDescription());
                    response.setCreatorName(metadata.getCreatorName());
                    response.setCreatedTime(metadata.getCreatedTime());
                    response.setUpdatedTime(metadata.getUpdatedTime());
                    response.setStatus(metadata.getStatus());
                    response.setAccessLevel(metadata.getAccessLevel());
                    response.setImagePath(url);
                    response.setUrl(metadata.getUrl());
                    response.setReviewStatus(metadata.getReviewStatus());
                    response.setDownloadNum(metadata.getDownloadNum());
                    response.setClickNum(metadata.getClickNum());
                    response.setShareNum(metadata.getShareNum());
                    response.setFavoriteNum(metadata.getFavoriteNum());

                    return response;
                }))
                .collect(Collectors.toList());

        // 等待所有任务完成并收集结果
        List<DatasetResponse> result = futures.stream()
                .map(future -> {
                    try {
                        return future.get();
                    } catch (Exception e) {
                        logger.error("Error fetching dataset response", e);
                        return null;
                    }
                })
                .filter(response -> response != null && response.getUrl() != null)
                .collect(Collectors.toList());

        executor.shutdown(); // 关闭线程池
        return result;
    }

    // 根据标签 返回数据集（公开）
    @GetMapping("/getDatasetsByTags")
    public List<DatasetResponse> getDatasetsByTags(@RequestParam String tag) {
        // 查询所有匹配标签的数据集标签
        List<DatasetTags> tagsList = datasetTagsService.getTagsByTags(tag);

        // 提取所有匹配标签的数据集ID
        List<Long> datasetIds = tagsList.stream()
                .map(DatasetTags::getDatasetId)
                .collect(Collectors.toList());

        // 查询所有匹配的数据集元数据
        List<DatasetMetadata> allMetadataList = datasetMetadataService.getDatasetsByIds(datasetIds);

        // 过滤出 access_level 为 public 的数据集
        List<DatasetMetadata> publicMetadataList = allMetadataList.stream()
                .filter(metadata -> "public".equals(metadata.getAccessLevel()))
                .collect(Collectors.toList());

        // 获取 publicMetadataList 中的 datasetIds 集合
        Set<Long> publicDatasetIds = publicMetadataList.stream()
                .map(DatasetMetadata::getDatasetId)
                .collect(Collectors.toSet());

        // 根据 publicDatasetIds 过滤 tagsList
        List<DatasetTags> publicTagsList = tagsList.stream()
                .filter(tagItem -> publicDatasetIds.contains(tagItem.getDatasetId()))
                .collect(Collectors.toList());

        // 创建线程池
        ExecutorService executor = Executors.newFixedThreadPool(10);

        // 并行处理，获取 MinIO 中的 URL
        List<Future<DatasetResponse>> futures = publicMetadataList.stream()
                .map(metadata -> executor.submit(() -> {
                    String datasetId = metadata.getDatasetId().toString();
                    String url = minioService.getImageUrlWithAnyFormat("image/" + datasetId);
                    logger.info("Generated URL for dataset {}: {}", datasetId, url);

                    // 收集所有匹配的标签
                    DatasetResponse response = new DatasetResponse();
                    response.setDatasetId(metadata.getDatasetId());
                    response.setName(metadata.getName());
                    response.setTags(getTagsByDatasetId(metadata.getDatasetId()));  // 确保收集到所有标签
                    response.setDescription(metadata.getDescription());
                    response.setCreatorName(metadata.getCreatorName());
                    response.setCreatedTime(metadata.getCreatedTime());
                    response.setUpdatedTime(metadata.getUpdatedTime());
                    response.setStatus(metadata.getStatus());
                    response.setAccessLevel(metadata.getAccessLevel());
                    response.setImagePath(url);  // 确保从 MinIO 获取 URL
                    response.setUrl(metadata.getUrl());
                    response.setReviewStatus(metadata.getReviewStatus());
                    response.setDownloadNum(metadata.getDownloadNum());
                    response.setClickNum(metadata.getClickNum());
                    response.setShareNum(metadata.getShareNum());
                    response.setFavoriteNum(metadata.getFavoriteNum());

                    return response;
                }))
                .collect(Collectors.toList());

        // 等待所有任务完成并收集结果
        List<DatasetResponse> result = futures.stream()
                .map(future -> {
                    try {
                        return future.get();
                    } catch (Exception e) {
                        logger.error("Error fetching dataset response", e);
                        return null;
                    }
                })
                .filter(response -> response != null && response.getUrl() != null)
                .collect(Collectors.toList());

        executor.shutdown(); // 关闭线程池
        return result;
    }

    @NotNull
    private DatasetResponse getDatasetResponse(DatasetMetadata metadata, List<String> tags) {
        DatasetResponse response = new DatasetResponse();
        response.setDatasetId(metadata.getDatasetId());
        response.setName(metadata.getName());
        response.setDescription(metadata.getDescription());
        response.setCreatorName(metadata.getCreatorName());
        response.setCreatedTime(metadata.getCreatedTime());
        response.setUpdatedTime(metadata.getUpdatedTime());
        response.setStatus(metadata.getStatus());
        response.setAccessLevel(metadata.getAccessLevel());
        response.setImagePath(metadata.getImagePath());
        response.setUrl(metadata.getUrl());
        response.setReviewStatus(metadata.getReviewStatus());
        response.setDownloadNum(metadata.getDownloadNum());
        response.setClickNum(metadata.getClickNum());
        response.setShareNum(metadata.getShareNum());
        response.setFavoriteNum(metadata.getFavoriteNum());
        response.setTags(tags);
        return response;
    }

    @NotNull
    private List<DatasetResponse> getDatasetResponses(List<DatasetMetadata> metadataList) {
        return metadataList.stream().map(metadata -> {
            List<String> tags = datasetTagsService.getTagsByDatasetId(metadata.getDatasetId())
                    .stream()
                    .map(DatasetTags::getTag)
                    .collect(Collectors.toList());

            return getDatasetResponse(metadata, tags);
        }).collect(Collectors.toList());
    }


    // 增加数据集的share_num
    @PostMapping("/shareDataset")
    public R shareDataset(@RequestBody String jsonString) {

        JSONObject jsonObject = new JSONObject(jsonString);
        String targetId = jsonObject.getString("targetId");

        // 获取数据集元数据
        DatasetMetadata metadata = datasetMetadataService.getById(targetId);
        System.out.println("分享量");
        System.out.println(targetId);
        System.out.println(metadata);

        if (metadata != null && "public".equals(metadata.getAccessLevel())) {
            // 增加分享次数
            datasetMetadataService.incrementShareNum(Long.valueOf(targetId));

            return R.ok(metadata.getUrl());
        } else {
            return R.failure("数据集不存在或不是公开数据集");
        }
    }

    // 增加数据集的click_num
    @PostMapping("/clickDataset")
    public R clickDataset(@RequestBody String jsonString) {

        JSONObject jsonObject = new JSONObject(jsonString);
        String targetId = jsonObject.getString("targetId");

        // 获取数据集元数据
        DatasetMetadata metadata = datasetMetadataService.getById(targetId);
        System.out.println("分享量");
        System.out.println(targetId);
        System.out.println(metadata);

        if (metadata != null && "public".equals(metadata.getAccessLevel())) {
            // 增加点击次数
            datasetMetadataService.incrementClickNum(Long.valueOf(targetId));

            return R.ok("点击量+1");
        } else {
            return R.failure("数据集不存在或不是公开数据集");
        }
    }

    // 增加数据集的favorite_num
    @PostMapping("/favoriteDataset")
    public R favoriteDataset(@RequestBody String jsonString) {

        JSONObject jsonObject = new JSONObject(jsonString);
        String targetId = jsonObject.getString("targetId");

        // 获取数据集元数据
        DatasetMetadata metadata = datasetMetadataService.getById(targetId);
        System.out.println("分享量");
        System.out.println(targetId);
        System.out.println(metadata);

        if (metadata != null && "public".equals(metadata.getAccessLevel())) {
            // 增加收藏次数
            datasetMetadataService.incrementFavoriteNum(Long.valueOf(targetId));

            return R.ok("收藏量+1");
        } else {
            return R.failure("数据集不存在或不是公开数据集");
        }
    }

    private List<String> getTagsByDatasetId(Long datasetId) {
        return datasetTagsService.getTagsByDatasetId(datasetId).stream()
                .map(DatasetTags::getTag)
                .collect(Collectors.toList());
    }

}
